<template>
  <div id="approve-list" class="manage-pos">
    <tag-box>
      <template v-slot:approve>
        <template v-if="!showChild">
          <div class="opentype-tag"
               :class="{'choose-bg-tag': apiType === 'running'}"
               @click="toggleStatus('running')"
          >进行中的流程</div>
          <div class="opentype-tag opentype-tag-2"
               :class="{'choose-bg-tag': apiType === 'finish'}"
               @click="toggleStatus('finish')"
          >已结束流程</div>
        </template>
        <template v-if="showChild">
          <div v-if="openType === 1" class="opentype-tag choose-bg-tag">流程审批进度历史</div>
          <div v-if="openType === 2" class="opentype-tag choose-bg-tag">请假单详情</div>
        </template>
      </template>
    </tag-box>
    <div style="height: 26px;" v-show="!showChild"></div>
    <div class="dep_top" v-show="!showChild">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="流程名称">
                <a-input
                  v-model="formData.name"
                  placeholder="请输入"
                ></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="标识key">
                <a-input
                  v-model="formData.key"
                  placeholder="请输入"
                ></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
            <span class="table-edit-submitButtons">
              <a-button class="ml8" @click="query">查询</a-button>
              <a-button type="primary" class="ml8" @click="resetParams">重置</a-button>
            </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </div>
    <div class="dep_main" v-show="!showChild">
      <a-row>
        <a-col :span="6" style="text-align: left;margin-bottom: 8px;">
          <a-button type="danger" :disabled="isDelete" @click="() => removeApply()">删除</a-button>
        </a-col>
      </a-row>
      <a-table
        bordered
        :scroll="scroll"
        ref="table"
        size="default"
        :columns="columns"
        :row-key="(r, index) => index.toString()"
        :row-selection="rowSelection"
        :data-source="listData"
        :pagination="paginationInfo"
        :loading="loading"
        @change="handleTableChange">
        <template slot="action" slot-scope="text, record, index">
          <a href="javascript:void(0);" style="color: blue;" @click="lookHistory(record)">审批详情</a>
          <a-divider type="vertical" />
          <a href="javascript:void(0);" style="color: #999;" @click="lookDetail(record)">请假详情</a>
          <a-divider type="vertical" />
          <a href="javascript:void(0);" style="color: red;" @click="removeApply(record.id)">删除</a>
        </template>
      </a-table>
    </div>
    <transition name="slide-fade">
      <div class="popContainer" v-if="showChild">
        <historic-detail
          v-if="openType === 1"
          :show-child.sync="showChild"
          :procInstId="procInstId"></historic-detail>
        <apply-detail
          v-if="openType === 2"
          :show-child.sync="showChild"
          :detail-info = "detailInfo"
        ></apply-detail>
      </div>
    </transition>
    <a-modal
      title="确认删除"
      :visible="reasonVisible"
      :confirm-loading="confirmLoading"
      @ok="deleteSubmit"
      @cancel="deleteCancel"
    >
      <a-input type="textarea" rows="4" placeholder="请输入删除原因" v-model="deleteReason"></a-input>
    </a-modal>
  </div>
</template>
<script>
import { ApplyDetail}  from './modules/ApplyComp'
import { TagBox } from '@/myComponents'
import HistoricDetail from '@/views/leaveManage/modules/HistoricDetail'
import { getAction, postFormAction } from '@/api/process'
export default {
  name: 'ApplyManage',
  components: {
    TagBox,
    HistoricDetail,
    ApplyDetail
  },
  data () {
    return {
      formData: {
        name: '',
        key: ''
      },
      isDelete: true,
      detailInfo: {},
      openType: 1,
      showChild: false,
      paginationInfo: {
        showSizeChanger: true,
        total: 0,
        current: 1,
        pageSizeOptions: ['5', '10', '15'],
        pageSize: 10,
        params: {}
      },
      selectedRowKeys: [],
      rowSelection: {
        fixed: true,
        columnWidth: 50,
        selectedRowKeys: [],
        onChange: (selectedRowKeys, selectedRows) => {
          this.rowSelection.selectedRowKeys = selectedRowKeys
          const ids = selectedRows.map((value, key) => {
            let { id } = value
            return id
          })
          this.selectedRows = ids
          if (selectedRows.length === 0) {
            this.isDelete = true
          } else {
            this.isDelete = false
          }
        }
      },
      columns: null,
      runningColumns: [
        {
          title: '流程实例ID',
          width: 150,
          align: 'center',
          dataIndex: 'id'
        },
        {
          title: '流程名称',
          width: 150,
          align: 'center',
          dataIndex: 'name'
        },
        {
          title: '申请人',
          width: 150,
          dataIndex: 'applyer',
          align: 'center'
        },
        {
          title: '标识Key',
          width: 150,
          dataIndex: 'key',
          align: 'center'
        },
        {
          title: '版本',
          width: 150,
          align: 'center',
          dataIndex: 'version',
          customRender: function (t, r, index) {
            return 'v.' + t
          }
        },
        {
          title: '当前环节',
          width: 150,
          dataIndex: 'currTaskName',
          align: 'center'
        },
        {
          title: '状态',
          width: 150,
          dataIndex: 'isSuspended',
          align: "center",
          sorter: (a,b) => a.isSuspended - b.isSuspended,
          customRender: (t, r, index) => {
            return t ? '已挂起' : '已激活'
          }
        },
        {
          title: '操作',
          width: 220,
          fixed: 'right',
          dataIndex: '',
          scopedSlots: { customRender: 'action' },
          align: 'center'
        }
      ],
      finishColumns: [
        {
          title: '流程实例ID',
          width: 150,
          align: 'center',
          dataIndex: 'id'
        },
        {
          title: '流程名称',
          width: 150,
          align: 'center',
          dataIndex: 'name'
        },
        {
          title: '申请人',
          width: 150,
          dataIndex: 'applyer',
          align: 'center'
        },
        {
          title: '标识Key',
          width: 150,
          dataIndex: 'key',
          align: 'center'
        },
        {
          title: '版本',
          width: 150,
          align: 'center',
          dataIndex: 'version',
          customRender: function (t, r, index) {
            return 'v.' + t
          }
        },
        {
          title: '审批结果',
          width: 150,
          dataIndex: 'result',
          align: "center",
          customRender: (text, record, index) => {
            let str = ''
            if (text === 2) {
              str = '已通过'
            }
            if (text === 3) {
              str = '已否决'
            }
            if (text === 4) {
              str = '发起人撤回'
            }
            if (text === 5) {
              str = '已删除'
            }
            return str
          }
        },
        {
          title: '操作',
          width: 220,
          fixed: 'right',
          dataIndex: '',
          scopedSlots: { customRender: 'action' },
          align: 'center'
        }
      ],
      selectedRows: null,
      tableData: [],
      listData: [],
      loading: false,
      url: {
        getRunningProcess:'/actProcessIns/getRunningProcess', // 进行中的流程
        deleteProcessIns:'/actProcessIns/delInsByIds/',
        updateInsStatus:'/actProcessIns/updateInsStatus/',
        getFinishedProcess:'/actProcessIns/getFinishedProcess', // 已结束流程
        delHistoricIns:'/actProcessIns/delHistoricInsByIds/',
        detailInfo: '/actBusiness/getForm'
      },
      apiType: 'running',
      scroll: {
        x: 1220
      },
      confirmLoading: false,
      deleteReason: '',
      reasonVisible: false,
      deleteId: null
    }
  },
  computed: {
    userInfo () {
      return this.$store.getters.userInfo
    }
  },
  created() {
    this.columns = this.runningColumns
    this.apiType = 'running'
    this.getApplyList()
  },
  methods: {
    showDataLocal () {
      this.loading = true
      const tableData = this.tableData
      const num = this.paginationInfo.current
      const size = this.paginationInfo.pageSize
      this.listData = tableData.slice((num -1)*size, size*num)
      this.loading = false
    },
    handleTableChange (pagination, filters, sorter) {
      this.paginationInfo = pagination;
      this.showDataLocal()
    },
    toggleStatus (status) {
      this.apiType = status
      if (status === 'running') {
        this.scroll = {
          x: 1220
        }
        this.columns = this.runningColumns
      } else {
        this.columns = this.finishColumns
        this.scroll = {
          x: 1070
        }
      }
      this.getApplyList()
    },
    async getApplyList () {
      const params = {
        _t: Date.parse(new Date()) / 1000,
        loginUserId: this.userInfo.id,
        name: '',
        key: '',
        pageNum: 1,
        pageSize: 10
      }
      Object.assign(params, this.formData)
      let _url = ''
      _url = this.apiType === 'running' ? this.url.getRunningProcess : this.url.getFinishedProcess
      this.loading = true
     const data = await getAction(_url, params)
      this.loading = false
      // const data = list
      if (data.success) {
        this.paginationInfo.total = data.result.length
        this.tableData = data.result
        this.listData = this.tableData.slice(0, this.paginationInfo.pageSize)
      } else {
        this.paginationInfo.total = 0
        this.tableData = []
        this.listData = []
        this.$message.warning(data.message)
      }
    },
    // 查询
    query () {
      this.paginationInfo.current = 1
      this.paginationInfo.pageSize = 10
      this.getApplyList()
    },
    resetParams () {
      this.paginationInfo.current = 1
      this.paginationInfo.pageSize = 10
      this.formData.name = ''
      this.formData.key = ''
      this.getApplyList()
    },
    lookHistory (row) {
      this.showChild = true
      this.openType = 1
      this.procInstId = row.id
    },
    lookDetail (row) {
      console.log('lookDetail', row)
      this.openType = 2
      this.getDetailInfo(row)
    },
    deleteSubmit () {
      const _this = this
      let _url = ''
      _url = this.apiType === 'running' ? this.url.deleteProcessIns : this.url.delHistoricIns
      _this.confirmLoading = true
      if (!_this.deleteId) {
        this.deleteId = this.selectedRows.join(',')
      }
      postFormAction(_url + this.deleteId, {reason: _this.deleteReason}).then(res => {
        if (res.success) {
          _this.paginationInfo.current = 1
          _this.paginationInfo.pageSize = 10
          _this.paginationInfo.params.key = ''
          _this.paginationInfo.params.name = ''
          _this.rowSelection.selectedRowKeys = []
          _this.getApplyList()
        } else {
          _this.$message.warning(res.message)
        }
        _this.isDelete = true
      }).catch(error => {
        console.log(error)
      }).finally( () => {
        _this.confirmLoading = false
        _this.deleteForm = null
        _this.reasonVisible = false
        _this.deleteReason = null
      })
    },
    deleteCancel () {
      this.reasonVisible = false
    },
    removeApply (id) {
      this.deleteId = id
      this.reasonVisible = true
    },
    getDetailInfo (r) {
      const params = {
        _t: parseInt(new Date().getTime() / 1000),
        tableId: r.tableId,
        tableName: r.tableName,
        loginUserId: this.userInfo.id
      }
      getAction(this.url.detailInfo, params).then(res => {
        if (res.success) {
          this.detailInfo = res.result
          this.showChild = true
        }
      }).catch(error => {
        console.log(error)
      })
    },
  }
}
</script>

<style scoped>

</style>
